% Function : statistics for box plot
% Parameter:
%   data: data(matrix or vector)
% Return:
%   Upper: the upper limit(vector or scalar)
%   Lower: the lower limit(vector or scalar)
%   Q    : each column is the 25th percentile , median and 75 percentile(vector or matrix)
% Note:
% When input is a matrix, Upper is the upper limit for each column
% as well as Lower
function [Upper, Lower, Q] = Box(data)
    if isrow(data)
        data = data';
    end

    [m, n] = size(data);    % size of data
    sdat   = sort(data);    % sort data

    % check number of rows
    if m < 3
        error('number of rows less than 3');
    end

    % Qi
    Q = zeros(3, n);
    for i = 1 : 3
        t       = i * (m + 1) / 4;
        l       = floor(t);
        u       = ceil(t);
        if l == u
            Q(i, :) = sdat(t, :);
        else
            Q(i, :) = sdat(l, :) * (t - l) + sdat(u, :) * (u - t);
        end
    end

    IQR = Q(3, :) - Q(1, :);

    Upper = Q(3, :) + 1.5 * IQR;
    Lower = Q(1, :) - 1.5 * IQR;
end
